package com.xbongbong.pro.aiassistant.handle;

import com.alibaba.fastjson.JSONObject;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.domain.entity.ext.PaasFormEntityExt;
import com.xbongbong.paas.enums.FlowStatusEnum;
import com.xbongbong.paas.help.UserAndDepartmentHelp;
import com.xbongbong.paas.model.PaasFormModel;
import com.xbongbong.paas.pojo.UserSimpPojo;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.pro.aiassistant.abstracts.AbstractAiAssistantStrategyHandle;
import com.xbongbong.pro.aiassistant.service.SmartSettingsEsService;
import com.xbongbong.pro.aiassistant.service.SsDistributeSaveService;
import com.xbongbong.pro.aiassistant.service.SsHistoryService;
import com.xbongbong.pro.aiassistant.service.SsMessageMergeService;
import com.xbongbong.pro.constant.AiAssistantConstant;
import com.xbongbong.pro.constant.I18nStringConstant;
import com.xbongbong.pro.domain.entity.AiAssistantEntity;
import com.xbongbong.pro.domain.entity.AiAssistantHistoryEntity;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.smartsettings.enums.AiAssistantPushTypeEnum;
import com.xbongbong.pro.enums.smartsettings.enums.SmartActionTypeEnum;
import com.xbongbong.pro.message.pojo.PushRefTypePojo;
import com.xbongbong.pro.message.pojo.dto.MessageRabbitMqDTO;
import com.xbongbong.pro.rabbitmq.producer.AiAssistantBaseProducer;
import com.xbongbong.pro.service.toolbox.smartsettings.help.SmartSettingsHelp;
import com.xbongbong.pro.smartsettings.pojo.AddOrUpdateHistoryPojo;
import com.xbongbong.pro.smartsettings.pojo.SsExecutorPojo;
import com.xbongbong.pro.smartsettings.pojo.SsExecutorUserIdPojo;
import com.xbongbong.pro.smartsettings.pojo.SsMessageMergePojo;
import com.xbongbong.pro.smartsettings.pojo.dto.RunStrategyDTO;
import com.xbongbong.pro.smartsettings.pojo.dto.SmartStrategyRabbitMqDTO;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.domain.entity.CommunicatePlanUserEntity;
import com.xbongbong.saas.domain.entity.UserTeamEntity;
import com.xbongbong.saas.domain.entity.ext.CommunicatePlanEntityExt;
import com.xbongbong.saas.enums.UserTeamEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.CommunicatePlanEnum;
import com.xbongbong.saas.enums.business.CustomerManagementEnum;
import com.xbongbong.saas.enums.business.ProductEnum;
import com.xbongbong.saas.model.CommunicatePlanModel;
import com.xbongbong.saas.model.CommunicatePlanUserModel;
import com.xbongbong.saas.service.toolbox.help.UserTeamHelp;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.model.UserModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

/**
 * @author 吴峰
 * @date 2020/09/17 15:21
 */
@Service("saasAiAssistantStrategyHandle")
public class SaasAiAssistantStrategyHandle extends AbstractAiAssistantStrategyHandle implements AiAssistantStrategyHandle {

    private static final Logger LOGGER = LoggerFactory.getLogger(SaasAiAssistantStrategyHandle.class);

    @Resource
    private SsHistoryService ssHistoryService;
    @Resource
    private SmartSettingsEsService smartSettingsEsService;
    @Resource
    private UserAndDepartmentHelp userAndDepartmentHelp;
    @Resource
    private SsMessageMergeService ssMessageMergeService;
    @Resource
    private SmartSettingsHelp smartSettingsHelp;
    @Resource
    private AiAssistantBaseProducer aiAssistantBaseProducer;
    @Resource
    private UserTeamHelp userTeamHelp;
    @Resource
    private SsDistributeSaveService ssDistributeSaveService;
    @Resource
    private PaasFormModel paasFormModel;
    @Resource
    private CommunicatePlanModel communicatePlanModel;
    @Resource
    private CommunicatePlanUserModel communicatePlanUserModel;
    @Resource
    private UserModel userModel;

    @Override
    public void executionStrategy(SmartStrategyRabbitMqDTO rabbitMqDTO, RunStrategyDTO runStrategyDTO) {
        String corpid = rabbitMqDTO.getCorpid();
        Boolean isTest = runStrategyDTO.getIsTest();
        AiAssistantEntity aiAssistantEntity = rabbitMqDTO.getAiAssistantEntity();
        // 获取该策略的数据id
        List<Long> dataIdList = getDataIds(rabbitMqDTO);
        if (CollectionsUtil.isEmpty(dataIdList)) {
            return;
        }
        Integer businessType = aiAssistantEntity.getBusinessType();
        // 查询历史记录
        List<AiAssistantHistoryEntity> historyList = getHistoryList(dataIdList, corpid, aiAssistantEntity.getId());
        // 对历史记录以及执行次数进行整理
        AddOrUpdateHistoryPojo addOrUpdateHistoryPojo = getAddOrUpdateList(historyList, dataIdList, aiAssistantEntity);
        List<AiAssistantHistoryEntity> updateList = addOrUpdateHistoryPojo.getUpdateList();
        List<AiAssistantHistoryEntity> addList = addOrUpdateHistoryPojo.getAddList();
        if (CollectionsUtil.isEmpty(addList) && CollectionsUtil.isEmpty(updateList)) {
            return;
        }
        List<PaasFormDataEntityExt> formDataList = smartSettingsEsService.getSaasDataList(corpid, businessType, dataIdList);
        // 获取执行人，拼装执行人（将部门，角色，人员，负责人，协同人，对应级主管）
        List<SsExecutorPojo> executorUserList = getExecutorUserList(aiAssistantEntity, dataIdList, formDataList);

        // 聚合
        List<SsMessageMergePojo> ssMessageMergeList = ssMessageMergeService.getMessageMergeList(executorUserList, aiAssistantEntity, addList, updateList);

        SmartActionTypeEnum smartActionTypeEnum = SmartActionTypeEnum.getByCode(aiAssistantEntity.getAction());
        switch (smartActionTypeEnum) {
            case MESSAGE:
                sendDingTalkMessage(aiAssistantEntity, ssMessageMergeList, addList, updateList, formDataList, runStrategyDTO);
                break;
            case ADD_COMMUNICATE_PLAN:
                communicatePlanDistributeSave(aiAssistantEntity, executorUserList, addList, updateList, formDataList);
                break;
            case SMS:
                // 短信
                smsDistributeSave(formDataList, addList, updateList, aiAssistantEntity, isTest);
            default:
                break;
        }
    }

    @Override
    public List<SsExecutorPojo> getExecutorUserList(AiAssistantEntity aiAssistantEntity, List<Long> dataIdList, List<PaasFormDataEntityExt> formDataList) {
        String corpid = aiAssistantEntity.getCorpid();
        Integer businessType = aiAssistantEntity.getBusinessType();
        List<SsExecutorPojo> ssExecutorList = new ArrayList<>();
        // // 当前需要执行的人员
        SsExecutorUserIdPojo ssExecutorUserIdPojo = getExecUserIds(aiAssistantEntity);
        Set<String> execUserIds = ssExecutorUserIdPojo.getExecUserIds();
        // 负责人
        Set<Integer> managerLevels = ssExecutorUserIdPojo.getManagerLevels();
        // 协同人
        Set<Integer> coordinatorLevels = ssExecutorUserIdPojo.getCoordinatorLevels();
// 关联合同
        Set<Integer> linkContractLevels = ssExecutorUserIdPojo.getLinkContractLevels();
        Set<Integer> linkWareHouseLevels = ssExecutorUserIdPojo.getLinkWareHouseLevels();
        Set<Integer> linkPurchaseLevels = ssExecutorUserIdPojo.getLinkPurchaseLevels();
        // 动态人员
        // {data1:[userId1,userId2]}
        Set<Long> dataIds = new HashSet<>();
        if (Objects.equals(XbbRefTypeEnum.PRODUCT.getCode(), businessType)) {
            Set<Long> parentIdList = new HashSet<>();
            for (PaasFormDataEntityExt entityExt : formDataList) {
                JSONObject data = entityExt.getData();
                Long parentId = data.getLong(ProductEnum.PARENT_ID.getAttr());
                if (Objects.equals(parentId, 0L)) {
                    parentIdList.add(entityExt.getId());
                } else {
                    parentIdList.add(parentId);
                }
            }
            dataIds.addAll(parentIdList);
        } else {
            dataIds = new HashSet<>(dataIdList);
        }
        Map<Long, List<String>> mainUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Map<Long, List<String>> coUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        // 全部执行人
        Set<String> allUserIdIn = new HashSet<>();
        // 将角色，部门，员工放进全部执行人中
        allUserIdIn.addAll(execUserIds);
        // 负责人 协同人获取
        if (!managerLevels.isEmpty() || !coordinatorLevels.isEmpty()) {
            if (UserTeamEnum.hasTeam(businessType)) {
                List<UserTeamEntity> userTeamEntityList = userTeamHelp.getUserTeamList(dataIds, corpid, businessType, false, null);
                for (UserTeamEntity entity : userTeamEntityList) {
                    if (!managerLevels.isEmpty() && Objects.equals(BasicConstant.ONE, entity.getIsMain())) {
                        // 负责人
                        setUserTeam(mainUserMap, entity.getUserId(), entity.getDataId());
                    } else if (!coordinatorLevels.isEmpty()) {
                        // 协同人
                        setUserTeam(coUserMap, entity.getUserId(), entity.getDataId());
                    }
                    allUserIdIn.add(entity.getUserId());
                }
            }
        }
        Map<Long, Set<String>> linkContractOwnerIdMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Map<Long, Set<String>> linkPurchaseOwnerIdMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Map<Long, Set<String>> linkWareHouseOwnerIdMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        if (Objects.equals(XbbRefTypeEnum.PAYMENT.getCode(), businessType) && !linkContractLevels.isEmpty()) {
            // 回款对应的合同负责人
            linkContractOwnerIdMap = getLinkContrOrPurUserIds(formDataList, aiAssistantEntity);
        }
        if (Objects.equals(XbbRefTypeEnum.PAY_PLAN.getCode(), businessType) && !linkPurchaseLevels.isEmpty()) {
            // 付款对应的采购合同负责人
            linkPurchaseOwnerIdMap = getLinkContrOrPurUserIds(formDataList, aiAssistantEntity);
        }
        if (!linkWareHouseLevels.isEmpty()) {
            // 关联仓库
            linkWareHouseOwnerIdMap = getLinkWarehouseUserId(formDataList, aiAssistantEntity);
        }

        Long aiAssistantId = aiAssistantEntity.getId();
        Long formId = aiAssistantEntity.getFormId();
        Map<Long, Set<String>> dataAndUserId = new HashMap<>(formDataList.size());

        for (PaasFormDataEntityExt entityExt : formDataList) {
            Set<String> userIdIn = new HashSet<>();
            // 负责人
            Long dataId = entityExt.getId();
            if (!UserTeamEnum.hasTeam(businessType) && StringUtil.isNotEmpty(entityExt.getOwnerId()) ) {
                userIdIn.add(entityExt.getOwnerId());
            }
            if (!managerLevels.isEmpty() && mainUserMap.containsKey(dataId)) {
                List<String> managerUserIds = mainUserMap.get(dataId);
                userIdIn.addAll(managerUserIds);
            }
            if (!coUserMap.isEmpty() && coUserMap.containsKey(dataId)) {
                // 协同人
                List<String> managerUserIds = coUserMap.get(dataId);
                userIdIn.addAll(managerUserIds);
            }
            if (!linkContractLevels.isEmpty() && linkContractOwnerIdMap.containsKey(dataId)) {
                // 回款对应的合同负责人
                userIdIn.addAll(linkContractOwnerIdMap.get(dataId));
            }
            if (!linkPurchaseLevels.isEmpty() && linkPurchaseOwnerIdMap.containsKey(dataId)) {
                // 付款对应的采购合同负责人
                userIdIn.addAll(linkPurchaseOwnerIdMap.get(dataId));
            }
            if (!linkWareHouseLevels.isEmpty() && linkWareHouseOwnerIdMap.containsKey(dataId)) {
                // 关联仓库
                userIdIn.addAll(linkWareHouseOwnerIdMap.get(dataId));
            }
            dataAndUserId.put(dataId, userIdIn);
            allUserIdIn.addAll(userIdIn);
        }
        // 执行人实体
        List<UserEntity> execUserList = userModel.getByUserIdIn(corpid, allUserIdIn);
        Map<String, UserEntity> userMap = new HashMap<>(execUserList.size());
        execUserList.forEach(item->{
            userMap.put(item.getUserId(), item);
        });
        formDataList.forEach(item->{
            Long dataId = item.getId();
            Set<String> userIdIn = dataAndUserId.get(dataId);
            execUserIds.addAll(userIdIn);
            List<UserEntity> list = new ArrayList<>();
            execUserIds.forEach(userId->{
                if (userMap.containsKey(userId)) {
                    list.add(userMap.get(userId));
                }
            });
            // 拼接执行人数据
            SsExecutorPojo pojo = new SsExecutorPojo(aiAssistantId, formId, dataId, new ArrayList<>(execUserIds), list);
            ssExecutorList.add(pojo);
        });
        return ssExecutorList;
    }

    @Override
    public void sendDingTalkMessage(AiAssistantEntity aiAssistantEntity, List<SsMessageMergePojo> messageMergeList, List<AiAssistantHistoryEntity> addList,
                                    List<AiAssistantHistoryEntity> updateList, List<PaasFormDataEntityExt> dataList, RunStrategyDTO runStrategyDTO) {

        // title内容
        String title = XbbRefTypeEnum.AI_ASSISTANT.getName() + PaasConstant.COLON + aiAssistantEntity.getName();
        String corpid = aiAssistantEntity.getCorpid();
        Integer businessType = aiAssistantEntity.getBusinessType();
        // 发送时间
        String sendTimeStr = getStrategyTime(aiAssistantEntity);
        // 产品库存预警、四个待跳转用到pushType
        AiAssistantPushTypeEnum pushTypeEnum = smartSettingsHelp.otherPush(aiAssistantEntity);
        // 产品消息
        boolean isProductFlag = Objects.equals(XbbRefTypeEnum.PRODUCT.getCode(), businessType);
        if (isProductFlag) {
            // 推送到库存查询：产品库存上限预警、产品库存下限预警、产品保质期预警
            if (Objects.isNull(pushTypeEnum)) {
                productMessageDistributeSave(aiAssistantEntity, messageMergeList, addList, updateList, dataList);
            } else {
                productStockMessageDistributeSave(aiAssistantEntity, messageMergeList, addList, updateList, dataList);
            }
            return;
        }
        Long sendTime = DateTimeUtil.getInt(sendTimeStr, DateTimeUtil.SDFYMDHM);
        String nameAttr = ssDistributeSaveService.getNameAttr(businessType);
        // 占位符的修改
        String placeHolder = smartSettingsHelp.getPlaceHolder(SaasMarkEnum.SAAS.getCode(), businessType);
        // 其他消息
        for (SsMessageMergePojo item : messageMergeList) {

            if (item.getDataIdList().size() > AiAssistantConstant.MAX_DATAID_LENGTH) {
                // 记录数据
                continue;
            }

            // 占位符替换
            String content = ssDistributeSaveService.handleContentPlaceholder(aiAssistantEntity.getMemo(), placeHolder, item.getDataIdList().size(), nameAttr);

            PushRefTypePojo.Options options = new PushRefTypePojo.Options(aiAssistantEntity.getAppId(), aiAssistantEntity.getMenuId(),
                    aiAssistantEntity.getFormId(), null, item.getDataIdList(), aiAssistantEntity.getSaasMark(),
                    aiAssistantEntity.getBusinessType(), aiAssistantEntity.getBusinessType());

            MessageRabbitMqDTO messageRabbitMqDTO = new MessageRabbitMqDTO(corpid, Collections.singletonList(item.getExcutorId()), item.getDataIdList(), 0,
                    sendTime, title, content, null, options);

            // 四个待推送有类型
            if (Objects.isNull(pushTypeEnum)) {
                pushTypeEnum = AiAssistantPushTypeEnum.getPushTypeBySubCode(aiAssistantEntity.getBusinessType());
            }
            if (Objects.equals(AiAssistantPushTypeEnum.UNKNOWN, pushTypeEnum)) {
                return;
            }
            try {
                // 分发数据
                aiAssistantBaseProducer.sendMessage(pushTypeEnum, messageRabbitMqDTO);
            } catch (Exception e) {
                LOGGER.error("SaasAiAssistantStrategyHandle.sendMessage 发送失败", e);
                // TODO 如果发送报错，是否需要中断执行，不再记录到执行记录中
            }
        }
        // 入库
        messageDataSave(corpid, addList, updateList);
    }

    /**
     * 产品
     * @param aiAssistantEntity
     * @param messageMergeList
     * @param addList
     * @param updateList
     * @param dataList
     */
    private void productMessageDistributeSave(AiAssistantEntity aiAssistantEntity, List<SsMessageMergePojo> messageMergeList, List<AiAssistantHistoryEntity> addList,
                                             List<AiAssistantHistoryEntity> updateList, List<PaasFormDataEntityExt> dataList) {
        List<Long> parentIdList = new ArrayList<>();
        String corpid = aiAssistantEntity.getCorpid();
        Map<Long, Long> productMap = new HashMap<>(dataList.size());
        for (PaasFormDataEntityExt entityExt : dataList) {
            JSONObject data = entityExt.getData();
            Long parentId = data.getLong(ProductEnum.PARENT_ID.getAttr());
            if (Objects.equals(parentId, 0L)) {
                parentIdList.add(entityExt.getId());
                continue;
            }
            productMap.put(entityExt.getId(), parentId);
        }
        AiAssistantPushTypeEnum pushTypeEnum = AiAssistantPushTypeEnum.getPushTypeBySubCode(aiAssistantEntity.getBusinessType());
        // 发送时间
        String sendTimeStr = getStrategyTime(aiAssistantEntity);
        Long sendTime = DateTimeUtil.getInt(sendTimeStr, DateTimeUtil.SDFYMDHM);
        // title内容
        String title = XbbRefTypeEnum.AI_ASSISTANT.getName() + PaasConstant.COLON + aiAssistantEntity.getName();
        // 占位符的修改
        String placeHolder = smartSettingsHelp.getPlaceHolder(SaasMarkEnum.SAAS.getCode(), aiAssistantEntity.getBusinessType());

        // 添加消息
        for (SsMessageMergePojo item : messageMergeList) {

            Set<Long> parentIdSet = new HashSet<>();
            for (Long productId : item.getDataIdList()) {
                if (productMap.containsKey(productId)) {
                    parentIdSet.add(productMap.get(productId));
                }
            }

            if (parentIdSet.size() > AiAssistantConstant.MAX_DATAID_LENGTH || parentIdSet.isEmpty()) {
                // 记录数据
                continue;
            }

            List<Long> productIdList = new ArrayList<>(parentIdSet);


            // 占位符替换
            String content = ssDistributeSaveService.handleContentPlaceholder(aiAssistantEntity.getMemo(), placeHolder, productIdList.size(), ProductEnum.NAME.getAttr());

            PushRefTypePojo.Options options = new PushRefTypePojo.Options(aiAssistantEntity.getAppId(), aiAssistantEntity.getMenuId(),
                    aiAssistantEntity.getFormId(), null, productIdList, aiAssistantEntity.getSaasMark(),
                    aiAssistantEntity.getBusinessType(), aiAssistantEntity.getBusinessType());

            MessageRabbitMqDTO messageRabbitMqDTO = new MessageRabbitMqDTO(corpid, Collections.singletonList(item.getExcutorId()), productIdList, 0,
                    sendTime, title, content, null, options);

            try {
                // 分发数据
                aiAssistantBaseProducer.sendMessage(pushTypeEnum, messageRabbitMqDTO);
            } catch (XbbException e) {
                LOGGER.error("", e);
            }
        }
        // 过虑子产品数据
        if (CollectionsUtil.isNotEmpty(addList)) {
            addList.removeIf(historyEntity -> !parentIdList.contains(historyEntity.getDataId()));
        }
        if (CollectionsUtil.isNotEmpty(updateList)) {
            updateList.removeIf(historyEntity -> !parentIdList.contains(historyEntity.getDataId()));
        }


        messageDataSave(corpid, addList, updateList);
    }


    /**
     * 产品库存
     * @param aiAssistantEntity
     * @param messageMergeList
     * @param addList
     * @param updateList
     * @param dataList
     */
    private void productStockMessageDistributeSave(AiAssistantEntity aiAssistantEntity, List<SsMessageMergePojo> messageMergeList, List<AiAssistantHistoryEntity> addList,
                                              List<AiAssistantHistoryEntity> updateList, List<PaasFormDataEntityExt> dataList) {
        String corpid = aiAssistantEntity.getCorpid();
        Long formId = aiAssistantEntity.getFormId();
        List<Long> childProductIdList = new ArrayList<>();
        for (PaasFormDataEntityExt dataEntityExt : dataList) {
            JSONObject data = dataEntityExt.getData();
            Long parentId = data.getLong(ProductEnum.PARENT_ID.getAttr());
            if (Objects.equals(parentId, 0L)) {
                continue;
            }
            childProductIdList.add(dataEntityExt.getId());
        }
        // 发送时间
        String sendTimeStr = getStrategyTime(aiAssistantEntity);
        Long sendTime = DateTimeUtil.getInt(sendTimeStr, DateTimeUtil.SDFYMDHM);
        // title内容
        String title = XbbRefTypeEnum.AI_ASSISTANT.getName() + PaasConstant.COLON + aiAssistantEntity.getName();
        // 占位符的修改
        String placeHolder = smartSettingsHelp.getPlaceHolder(SaasMarkEnum.SAAS.getCode(), aiAssistantEntity.getBusinessType());
        AiAssistantPushTypeEnum pushTypeEnum = smartSettingsHelp.otherPush(aiAssistantEntity);

        // 添加消息
        for (SsMessageMergePojo item : messageMergeList) {

            item.getDataIdList().retainAll(childProductIdList);

            if (item.getDataIdList().size() > AiAssistantConstant.MAX_DATAID_LENGTH || item.getDataIdList().isEmpty()) {
                // 记录数据
                continue;
            }

            List<Long> productIdList = new ArrayList<>(item.getDataIdList());


            // 占位符替换
            String content = ssDistributeSaveService.handleContentPlaceholder(aiAssistantEntity.getMemo(), placeHolder, productIdList.size(), ProductEnum.NAME.getAttr());

            PushRefTypePojo.Options options = new PushRefTypePojo.Options(aiAssistantEntity.getAppId(), aiAssistantEntity.getMenuId(),
                    formId, null, productIdList, aiAssistantEntity.getSaasMark(),
                    aiAssistantEntity.getBusinessType(), aiAssistantEntity.getBusinessType());

            MessageRabbitMqDTO messageRabbitMqDTO = new MessageRabbitMqDTO(corpid, Collections.singletonList(item.getExcutorId()), productIdList, 0,
                    sendTime, title, content, null, options);

            try {
                // 分发数据
                aiAssistantBaseProducer.sendMessage(pushTypeEnum, messageRabbitMqDTO);
            } catch (XbbException e) {
                LOGGER.error("", e);
            }
        }
        // 过虑子产品数据
        if (CollectionsUtil.isNotEmpty(addList)) {
            addList.removeIf(historyEntity -> !childProductIdList.contains(historyEntity.getDataId()));
        }
        if (CollectionsUtil.isNotEmpty(updateList)) {
            updateList.removeIf(historyEntity -> !childProductIdList.contains(historyEntity.getDataId()));
        }


        messageDataSave(corpid, addList, updateList);
    }

    /**
     * 新增访客--记录入库
     *
     * @param aiAssistantEntity 智能助手
     * @param executorList 执行人
     * @param addList  新增
     * @param updateList 更新
     * @param dataList 数据列表
     * @return
     * @throws
     * @author hongxiao
     * @date 2019-05-17 15:36
     * @version v1.0
     * @since v1.0
     */
    private void communicatePlanDistributeSave(AiAssistantEntity aiAssistantEntity, List<SsExecutorPojo> executorList, List<AiAssistantHistoryEntity> addList,
                                               List<AiAssistantHistoryEntity> updateList, List<PaasFormDataEntityExt> dataList) {
        String corpid = aiAssistantEntity.getCorpid();
        // 执行记录
        Map<Long, AiAssistantHistoryEntity> addHistoryMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Map<Long, AiAssistantHistoryEntity> updateHistoryMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        addList.forEach(item -> {
            addHistoryMap.put(item.getDataId(), item);
        });
        updateList.forEach(item -> {
            updateHistoryMap.put(item.getDataId(), item);
        });

        // 发送时间
        String sendTimeStr = getStrategyTime(aiAssistantEntity);
        Long sendTime = DateTimeUtil.getInt(sendTimeStr, DateTimeUtil.SDFYMDHM);


        PaasFormEntityExt paasFormEntity = paasFormModel.getByBusinessType(XbbRefTypeEnum.COMMUNICATE_PLAN.getCode(), corpid);
        Map<Long, SsExecutorPojo> executorMap = new HashMap<>(executorList.size());
        for (SsExecutorPojo ssExecutorPojo : executorList) {
            Long customerId = ssExecutorPojo.getDataId();
            executorMap.put(customerId, ssExecutorPojo);
        }

        for (PaasFormDataEntityExt customer : dataList) {
            // 客户id
            Long customerId = customer.getId();

            // 执行人
            SsExecutorPojo pojo = executorMap.get(customerId);
            if (Objects.isNull(pojo)) {
                continue;
            }
            List<UserEntity> userEntitys = pojo.getExecutorList();

            JSONObject communicatePlan = new JSONObject();
            JSONObject customerData = customer.getData();
            String customerName = customerData.getString(CustomerManagementEnum.NAME.getAttr());
            // 访客计划名称
            String name = customerName + I18nMessageUtil.getMessage(I18nStringConstant.COMMUNICATE_PLAN) + PaasConstant.LEFT_BRACKET + I18nMessageUtil.getMessage(AiAssistantConstant.AI_ASSISTANT_GENERATE) + PaasConstant.RIGHT_BRACKET;
            communicatePlan.put(CommunicatePlanEnum.LINK_CUSTOMER.getAttr(), customerId);
            communicatePlan.put(CommunicatePlanEnum.CUSTOMER_NAME_LINK_TEXT.getAttr(), customerName);
            communicatePlan.put(CommunicatePlanEnum.NAME.getAttr(), name);
            communicatePlan.put(CommunicatePlanEnum.MEMO.getAttr(), I18nMessageUtil.getMessage(AiAssistantConstant.AI_ASSISTANT_GENERATE_MEMO));
            try {
                List<String> executorTypeList = Arrays.asList("2");
                communicatePlan.put(CommunicatePlanEnum.EXECUTOR.getAttr(), executorTypeList);
                communicatePlan.put(CommunicatePlanEnum.NOTIFY_TYPE.getAttr(), "0");
                // 访客计划执行时间
                communicatePlan.put(CommunicatePlanEnum.COMMUNICATE_TIME.getAttr(), sendTime);
                // 访客计划备注以及名称
                CommunicatePlanEntityExt communicatePlanEntityExt = new CommunicatePlanEntityExt();
                BeanUtil.copyProperties(paasFormEntity, communicatePlanEntityExt);
                communicatePlanEntityExt.setFormId(paasFormEntity.getId());
                communicatePlanEntityExt.setData(communicatePlan);
                communicatePlanEntityExt.setDel(BasicConstant.ZERO);
                communicatePlanEntityExt.setId(null);
                communicatePlanEntityExt.setFlowStatus(FlowStatusEnum.NOT_NEED_APPROVAL.getType());
                // 创建人
                communicatePlanEntityExt.setCreatorId(PaasConstant.SYS_USER_ID);
                // 负责人
                communicatePlanEntityExt.setOwnerId(PaasConstant.SYS_USER_ID);
                communicatePlanEntityExt.setSerialNo("");
                communicatePlanEntityExt.setDepartmentId(0L);
                communicatePlanModel.insert(communicatePlanEntityExt);

                // 保存执行人
                List<UserSimpPojo> executorUserList = new ArrayList<>();
                List<CommunicatePlanUserEntity> planUserList = new ArrayList<>();
                for (UserEntity user : userEntitys) {
                    CommunicatePlanUserEntity planUser = new CommunicatePlanUserEntity();
                    planUser.setCorpid(corpid);
                    planUser.setDataId(communicatePlanEntityExt.getId());
                    planUser.setUserId(user.getUserId());
                    planUser.setUserName(user.getName());
                    planUser.setUserAvatar(user.getAvatar());
                    planUser.setIsCreator(BasicConstant.ZERO);
                    planUserList.add(planUser);

                    UserSimpPojo userSimpPojo = new UserSimpPojo();
                    userSimpPojo.setUserId(user.getUserId());
                    userSimpPojo.setName(user.getName());
                    executorUserList.add(userSimpPojo);
                }
                communicatePlanUserModel.insertBatch(planUserList);


            } catch (Exception e) {
                // 报错
                LOGGER.error("新增访客--记录入库", e);
            }
        }
        messageDataSave(corpid, addList, updateList);

    }

}
